<template>
    <div>
        <!-- 操作栏 -->
        <div style="margin-bottom: 12px;">
            <el-button-group>
                <el-button v-for="(label, key) in dataFields" :key="key" size="mini"
                    :type="currentField === key ? 'primary' : 'default'" @click="selectField(key)">
                    {{ label }}
                </el-button>
            </el-button-group>

            <el-button-group style="margin-left: 10px;">
                <el-button v-for="(label, days) in dateRanges" :key="days" size="mini"
                    :type="isQuickRangeActive(Number(days)) ? 'success' : 'default'"
                    @click="changeDateRange(Number(days))">
                    {{ label }}
                </el-button>
            </el-button-group>

            <el-date-picker v-model="customRange" type="daterange" size="mini" unlink-panels
                style="margin-left: 12px; width: 260px;" start-placeholder="开始日期" end-placeholder="结束日期"
                :picker-options="{ disabledDate: time => time.getTime() > Date.now() }" @change="onCustomRangeChange" />

            <el-button type="primary" size="mini" @click="toggleChartType" style="margin-left: 40px;">
                切换为{{ chartType === 'line' ? '柱状图' : '折线图' }}
            </el-button>

            <el-button type="primary" size="mini" @click="toggleMainType" style="margin-left: 40px;">
                切换为{{ main_type === 'charts' ? '表格明细' : '图表展示' }}
            </el-button>

            <!-- <el-button size="mini" type="primary" @click="showProductDialog = true" style="margin-left: 20px;">
        选择展示产品 (已选 {{ selectedProducts.length }}/{{ ourProductList.length + competeProductList.length }})
      </el-button> -->
        </div>

        <div>
            <ECharts :options="chartOptions" autoresize style="width: 95%; height: 65vh;"
                v-show="main_type === 'charts'" />
            <cTable @dialogEvent="tableDetailShow" tableHeight="65vh" :use_paginate="false" :tableColumn="tableColumn" :tableData="tableData" v-show="main_type === 'table'" style="width: 95%; height: 65vh;"></cTable>
        </div>

        <div style="text-align: center; padding-top: 10px;">
            <small>数据日期范围：{{ dateRangeTip }}</small>
        </div>

        <!-- 产品选择弹窗 -->
    <!-- <el-dialog  :visible.sync="showProductDialog" :modal="false" width="60%">
        <template #title>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                <span style="padding-right: 10px;">{{ detail_date }}</span>
                <span style="padding-right: 20px;">{{ detail_sku }}</span>
                
            </div>
        </template>
        <cTable :tableColumn="detail_column" :tableData="detail_data" :use_paginate="false" tableHeight="65vh"></cTable>

    </el-dialog> -->

  <el-dialog :visible.sync="showProductDialog" append-to-body top="5vh"  :modal="true" width="80%" class="aver_analyze_detail_dialog">
    <!-- 弹窗标题 -->
    <template #title>
      <div class="dialog-header">
        <span style="font-size: 18px; font-weight: bold;">{{ detail_date }}</span>
        <span style="padding-left: 20px; font-size: 18px; font-weight: bold;">{{ detail_sku }}</span>
      </div>
    </template>

    <!-- 数据指标展示卡片 -->
     <el-row type="flex" style="height: 40px; margin-bottom: 10px;">
        <el-col class="details-items">
            <div class="our"><span>我方销量：</span>{{ total_sales_our }}</div>
            <div class="compete"><span>竞品销量：</span>{{ total_sales_compete }}</div>
            
        </el-col>
        <el-col class="details-items">
            <div class="our"><span>我方均价：</span>{{ avg_price_our }}</div>
            <div class="compete"><span>竞品均价：</span>{{ aver_price_compete }}</div>
            
        </el-col>
        <el-col class="details-items">
            <div class="our"><span>我方加权价：</span>{{ weighted_avg_price_our }}</div>
            <div class="compete"><span>竞品加权价：</span>{{ weighted_avg_price_compete }}</div>
        </el-col>

        <el-col class="details-items">
              <el-button @click="toggleDetailType" :type="current_details.btn_type"  size="mini" >切换为{{ current_details.label }}</el-button>
        </el-col>
        
     </el-row>
    <!-- 表格展示 -->
    <cTable
      :tableColumn="detail_column"
      :tableData="detail_data"
      :use_paginate="false"
      tableHeight="65vh"
    />
  </el-dialog>


    </div>
</template>

<script>
import ECharts from 'vue-echarts';
import cTable from '@/components/Table'

export default {
    name: 'MultiMetricChart',
    components: { ECharts, cTable },
    props: {
        props_data: {
            default: () => ({})
        }
    },
    data() {
        return {
            chartType: 'line',
            chartOptions: {},
            all_data: {},
            main_type: 'charts',
            dateRangeTip: '',
            platform_sku:'',
            detail_date:'',
            detail_sku:'',
            selectedDays: 7,
            current_details:{label:'竞品数据', btn_type:'primary', type:'our'},

            aver_price_compete: 0,
            avg_price_our: 0,

            weighted_avg_price_compete: 0,
            weighted_avg_price_our: 0,

            total_sales_compete: 0,
            total_sales_our: 0,

            //   使用自定义组件table, 配置项需要遵循数据sysConfig.js
            tableColumn: {
                column: [
                    { label: '自增ID,唯一标识一条记录', key: 'id', isShow: false, type: 'text' },
                    { label: '日期', minWidth:100, key: 'date', isShow: true, type: 'text' },
                    { label: 'listing数量', minWidth:100, key: 'listing_count', isShow: true, type: 'row_many', column: 1, map: [[{ label: '我方', key: 'our' }, { label: '竞品', key: 'compete' }]] },
                    { label: '销量', key: 'sales', minWidth: 100, isShow: true, type: 'row_many', column: 1, map: [[{ label: '我方', key: 'our' }, { label: '竞品', key: 'compete' }]] },
                    { label: '加权单价', key: 'weighted_avg_price', minWidth: 100, isShow: true, type: 'row_many', column: 1, map: [[{ label: '我方', key: 'our' }, { label: '竞品', key: 'compete' }]] },
                    { label: '平均单价', key: 'aver_price', minWidth: 100, isShow: true, type: 'row_many', column: 1, map: [[{ label: '我方', key: 'our' }, { label: '竞品', key: 'compete' }]] },
                    { label: '营业额', key: 'gmv',minWidth: 100,  isShow: true, type: 'row_many', column: 1, map: [[{ label: '我方', key: 'our' }, { label: '竞品', key: 'compete' }]] },
                    { label: '占比', key: 'counts_percent', minWidth: 100, isShow: true, type: 'row_many', column: 1, map: [[{ label: '我方', key: 'our' }, { label: '竞品', key: 'compete' }]] },
                ],
                btn: [{label: '详情',style: 'warning'}],
            },
            detail_column: {
                column:[
                    { label: '自增ID,唯一标识一条记录', key: 'id', isShow: false, type: 'text' },
                    { label: 'listing', minWidth:100, key: 'listing', isShow: true, type: 'text', clickEvent:row=>{window.open(`https://www.ebay.com/itm/${row.listing_id}`)}  },
                    { label: '销量', minWidth:100, key: 'sales', isShow: true, type: 'text' },
                    { label: '价格', minWidth:100, key: 'price', isShow: true, type: 'text' },
                    { label: 'listing', minWidth:100, key: 'listing_id', isShow: false, type: 'text'},
                    { label: '销售额',minWidth:100, key: 'gmv', isShow: true, type: 'text' },
                    { label: '平均价差', minWidth:100,key: 'aver_price_difference', isShow: true, type: 'row_many', column: 1, map: [[{ label: '对比我方', key: 'our' }, { label: '对比竞品', key: 'compete' }]] },
                    { label: '加权价差(未出售为0)',minWidth:100, key: 'weighted_price_difference', isShow: true, type: 'row_many', column: 1, map: [[{ label: '对比我方', key: 'our' }, { label: '对比竞品', key: 'compete' }]]  },
                    { label: '销售占比',minWidth:100, key: 'counts_percent', isShow: true, type: 'text' },
                ],
                btn: [
                ],
            },
            detail_column_our: {
                column:[
                    { label: '自增ID,唯一标识一条记录', key: 'id', isShow: false, type: 'text' },
                    { label: 'listing', minWidth:100, key: 'listing', isShow: true, type: 'text', clickEvent:row=>{window.open(`https://www.ebay.com/itm/${row.listing_id}`)}  },
                    { label: '销量', minWidth:100, key: 'sales', isShow: true, type: 'text' },
                    { label: '价格', minWidth:100, key: 'price', isShow: true, type: 'text' },
                    { label: 'listing', minWidth:100, key: 'listing_id', isShow: false, type: 'text'},
                    { label: '销售额',minWidth:100, key: 'gmv', isShow: true, type: 'text' },
                    { label: '平均价差', minWidth:100,key: 'aver_price_difference', isShow: true, type: 'row_many', column: 1, map: [[{ label: '对比我方', key: 'our' }, { label: '对比竞品', key: 'compete' }]] },
                    { label: '加权价差(未出售为0)',minWidth:100, key: 'weighted_price_difference', isShow: true, type: 'row_many', column: 1, map: [[{ label: '对比我方', key: 'our' }, { label: '对比竞品', key: 'compete' }]]  },
                    { label: '销售占比',minWidth:100, key: 'counts_percent', isShow: true, type: 'text' },
                ],
                btn: [
                ],
            },

            detail_column_compete: {
                column:[
                    { label: '自增ID,唯一标识一条记录', key: 'id', isShow: false, type: 'text' },
                    { label: 'listing', minWidth:100, key: 'listing', isShow: true, type: 'text', clickEvent:row=>{window.open(`https://www.ebay.com/itm/${row.listing_id}`)}  },
                    { label: '标题', key: 'title', isShow: true, type: 'text' },
                    { label: '主图', key: 'image', isShow: true, type: 'image' },
                    { label: 'listing', minWidth:100, key: 'listing_id', isShow: false, type: 'text'},
                    { label: '销量', minWidth:100, key: 'sales', isShow: true, type: 'text' },
                    { label: '价格', minWidth:100, key: 'price', isShow: true, type: 'text' },
                    { label: '销售额',minWidth:100, key: 'gmv', isShow: true, type: 'text' },
                    
                    { label: '销售占比',minWidth:100, key: 'counts_percent', isShow: true, type: 'text' },
                ],
                btn: [
                ],
            },


            detail_data:[],

            tableData: [],
            currentField: 'sales',
            customRange: null,
            ourProductList: [],
            competeProductList: [],
            selectedProducts: [],
            showProductDialog: false,
            chartData: [],
            dataFields: {
                sales: '销量',
                aver_price: '平均单价',
                weighted_avg_price: '加权单价',
                gmv: '销售额',
                counts_percent: '占比'
            },
            dateRanges: {
                7: '最近7天',
                15: '最近15天',
                30: '最近30天'
            }
        };
    },
    beforeMount() {
        this.$http('get', `/MapCompeteListing/details/${this.props_data.id}`, this.props_data).then(res => {
            // 这是之前的多列表的写法，既分为多个listing的写法
            //   const our_list = (res.data.our_listing || []).map(item => ({
            //     label: item.paltfrom_sku + '--' + item.listing_id,
            //     type: 'our'
            //   }))

            //   const compete_list = (res.data.compete_listing || []).map(item => ({
            //     label: '竞品--' + item.listing_id,
            //     type: 'compete'
            //   }))

            // 现在只有两个均值数据
            

            const our_list = { label: res.data.our_listing[0].paltfrom_sku, type: 'our' }

            this.platform_sku = res.data.our_listing[0].paltfrom_sku

            const compete_list = { label: '竞品产品', type: 'compete' }

            const { our_listing_aver, compete_listing_aver } = this.calc_history_percent(res.data.our_listing, res.data.compete_listing)


            our_list.history_json = our_listing_aver
            compete_list.history_json = compete_listing_aver

            this.ourProductList = our_list
            this.competeProductList = compete_list

            // const defaultOur = our_list.slice(0, 3).map(i => i.label)
            // const defaultCompete = compete_list.slice(0, 1).map(i => i.label)
            this.selectedProducts = [this.ourProductList.label, this.competeProductList.label]

            this.all_data = res.data
            this.generateMockData(this.selectedDays)

        })
    },
    methods: {

        toggleDetailType(){
            if(this.current_details.type === 'our'){

                this.current_details.type = 'compete'
                this.current_details.label = '我方数据'
                this.current_details.btn_type = 'warning'
                this.detail_column = this.detail_column_compete
                this.detail_data = this.details_compete
            }
            else {
                this.current_details.btn_type = 'primary'
                this.current_details.type = 'our'
                this.current_details.label = '竞品数据'
                this.detail_column = this.detail_column_our
                this.detail_data = this.details_our
            }
        },


        init_detail_info (){
            this.current_details = {
                type: 'our',
                label: '竞品数据',
                btn_type: 'primary'
            }
            this.detail_column = this.detail_column_our
        },

        /**
         * 点击表格的详情按钮的回调函数
         * @param {Boolean} if_dialog - 是否显示dialog
         * @param {Object} item - 配置项
         * @param {Object} row - 当前行数据
         */
        tableDetailShow(if_dialog, item, row){

            this.init_detail_info()
            let details_our = []
            let details_compete = []

            this.total_sales_our = row.sales.our
            this.total_sales_compete = row.sales.compete
            this.aver_price_compete = row.aver_price.compete
            this.avg_price_our = row.aver_price.our
            this.weighted_avg_price_compete = row.weighted_avg_price.compete
            this.weighted_avg_price_our = row.weighted_avg_price.our

            this.all_data.our_listing.forEach(item => {
                Object.entries(item.history_json).forEach(([key, value]) => {
                    if(key === row.date && value.price > 0){
                        details_our.push({
                            id: item.id,
                            listing: `${this.platform_sku} - ${item.listing_id}`,
                            listing_id: item.listing_id,
                            sales: value.sales,
                            price: value.price,
                            gmv: value.gmv,
                            date: key,

                            // 平均差价
                            aver_price_difference:{
                                our:this.float_data(value.price - row.aver_price.our),
                                compete :this.float_data(value.price - row.aver_price.compete),
                            },

                            // 加权价差
                            weighted_price_difference:{ 
                                our:row.weighted_avg_price.our >0 ? this.float_data(value.price - row.weighted_avg_price.our):0,
                                compete:row.weighted_avg_price.compete >0 ? this.float_data(value.price - row.weighted_avg_price.compete):0,
                            },
                            // 销售占比
                            counts_percent:  ((row.sales.compete + row.sales.our) > 0? (this.float_data(value.sales / (row.sales.compete + row.sales.our), 4) * 100).toFixed(2): '0.00') + '%'
                        })
                    }
                })
            })

            this.all_data.compete_listing.forEach(item => {
                Object.entries(item.history_json).forEach(([key, value]) => {
                    if(key === row.date && value.price > 0){
                        details_compete.push({

                            id: item.id,
                            listing: `竞品 - ${item.listing_id}`,
                            listing_id: item.listing_id,
                            title:item.title,
                            image:item.image_url,
                            sales: value.sales,
                            price: value.price,
                            gmv: value.gmv,
                            date: key,

                            // // 平均差价
                            // aver_price_difference: this.float_data(value.price - row.aver_price.compete),

                            // // 加权价差
                            // weighted_price_difference: row.weighted_avg_price.compete >0 ? this.float_data(value.price - row.weighted_avg_price.compete):0,

                            // 销售占比
                            counts_percent:  ((row.sales.compete + row.sales.our) > 0? (this.float_data(value.sales / (row.sales.compete + row.sales.our), 4) * 100).toFixed(2): '0.00') + '%'
                        })
                    }
                })
            })


            details_our.sort((a, b) => {
                return Number(b.sales || 0) - Number(a.sales || 0);
            });

            details_compete.sort((a, b) => {
                return Number(b.sales || 0) - Number(a.sales || 0);
            });

            this.details_our = details_our
            this.details_compete = details_compete
            
            this.detail_data = this.details_our
            this.detail_date = row.date
            this.detail_sku = this.platform_sku
            this.$nextTick(() => {this.showProductDialog = true;});
        },

        toggleMainType() {
            if (this.main_type == 'charts') {
                this.main_type = 'table'
            }
            else {
                this.main_type = 'charts'
            }
        },

        // 合计每个listing的历史所有数据 并分别计算占比
        calc_history_percent(our_listing, compete_listing) {
            let our_listing_aver = {};
            let compete_listing_aver = {};

            // 遍历我们的 listing
            our_listing.forEach(item => {
                Object.entries(item.history_json).forEach(([key, value]) => {
                    if (!our_listing_aver[key]) {
                        our_listing_aver[key] = {
                            sales: 0,
                            listing_count: 0,
                            price: 0,
                            gmv: 0
                        };
                    }
                    our_listing_aver[key]["sales"] += parseInt(value["sales"]);
                    our_listing_aver[key]["listing_count"] += 1;
                    our_listing_aver[key]["price"] += parseFloat(value["price"]);
                    our_listing_aver[key]["gmv"] += parseFloat(value["gmv"]);
                });
            });

            // 遍历竞争 listing
            compete_listing.forEach(item => {
                Object.entries(item.history_json).forEach(([key, value]) => {
                    if (!compete_listing_aver[key]) {
                        compete_listing_aver[key] = {
                            sales: 0,
                            listing_count: 0,
                            price: 0,
                            gmv: 0
                        };
                    }
                    compete_listing_aver[key]["sales"] += parseInt(value["sales"]);
                    compete_listing_aver[key]["listing_count"] += 1;
                    compete_listing_aver[key]["price"] += parseFloat(value["price"]);
                    compete_listing_aver[key]["gmv"] += parseFloat(value["gmv"]);
                });

            });

            console.log("compete_listing==>", compete_listing_aver)

            // 计算平均价格、加权平均价格、占比
            Object.keys(our_listing_aver).forEach(key => {
                const ourData = our_listing_aver[key];
                const compData = compete_listing_aver[key] || {
                    sales: 0,
                    listing_count: 0,
                    price: 0,
                    gmv: 0
                };

                // 平均价格
                ourData.aver_price = this.float_data((ourData.price / ourData.listing_count));
                compData.aver_price = this.float_data(compData.listing_count > 0 ? (compData.price / compData.listing_count) : 0);

                // 加权平均价格
                ourData.weighted_avg_price = this.float_data(ourData.sales > 0 ? (ourData.gmv / ourData.sales) : 0);
                compData.weighted_avg_price = this.float_data(compData.sales > 0 ? (compData.gmv / compData.sales) : 0);

                // 销量占比
                const total_sales = ourData.sales + compData.sales;
                ourData.counts_percent = this.float_data(total_sales > 0 ? ourData.sales / total_sales : 0, 4);
                compData.counts_percent = this.float_data(total_sales > 0 ? compData.sales / total_sales : 0, 4);

                // 保存回去（如果你想修改 compete_listing_aver 结构)
                compete_listing_aver[key] = compData;
            });
            // 返回结果（可选）

            return {
                our_listing_aver,
                compete_listing_aver
            };
        },



        /**
         * 限制浮点数精度
         * @param {Number|String} val - 需要限制精度的数字|可转化位数字的字符串
         * @param {Number} [digist=2] - 精度
         * @return {Number} 限制了精度的数字
         * 
         * 注意数字默认是会去掉末尾的0的
         */
        float_data(val, digist = 2) {
            return parseFloat(parseFloat(val).toFixed(digist));
        },

        /**
         * 切换chart的type
         * @description bar/line
         */
        toggleChartType() {
            this.chartType = this.chartType === 'line' ? 'bar' : 'line';
            this.updateEchart();
        },

        selectField(field) {
            this.currentField = field;
            this.updateEchart();
        },
        changeDateRange(days) {
            this.selectedDays = days;
            this.customRange = null;
            this.generateMockData(days);
        },
        isQuickRangeActive(days) {
            return this.selectedDays === days && this.customRange === null;
        },
        onCustomRangeChange(range) {
            if (!range || range.length !== 2) return;
            const [start, end] = range;
            this.generateMockData(0, start, end);
        },
        onConfirmProductSelection() {
            this.showProductDialog = false;
            this.updateEchart();
        },


        /*
         *  这是之前的通过lisitng id 来找到对应的产品， 现在实际上只有两个产品
        generateMockData(days = 7, startDate = null, endDate = null) {
          const res = this.all_data || {};
          const allItems = [...(res.our_listing || []), ...(res.compete_listing || [])];
          const allProductNames = [...this.ourProductList, ...this.competeProductList].map(p => p.label);
    
          const result = [];
          let start, end;
          if (startDate && endDate) {
            start = new Date(startDate);
            end = new Date(endDate);
          } else {
            end = new Date();
            start = new Date();
            start.setDate(end.getDate() - (days - 1));
          }
    
          const allDates = [];
          const current = new Date(start);
          while (current <= end) {
            allDates.push(new Date(current));
            current.setDate(current.getDate() + 1);
          }
    
          let displayDates = allDates;
          if (allDates.length > 30) {
            const step = Math.floor((allDates.length - 1) / 29);
            const selected = [];
            for (let i = 0; i < 29; i++) {
              selected.push(allDates[i * step]);
            }
            selected.push(allDates[allDates.length - 1]);
            displayDates = selected;
          }
    
          displayDates.forEach(date => {
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const shortDate = `${month}-${day}`;
            const year = date.getFullYear();
            const fullDate = `${year}-${month}-${day}`;
            const row = { date: shortDate };
    
            allProductNames.forEach(product => {
              const matchItem = allItems.find(item => {
                const key = item.paltfrom_sku
                  ? `${item.paltfrom_sku}--${item.listing_id}`
                  : `竞品--${item.listing_id}`;
                return key === product;
              });
    
              const history = matchItem?.history_json?.[fullDate] || { gmv: 0, price: 0, sales: 0 };
    
              row[product] = {
                sales: history.sales || 0,
                gmv: history.gmv || 0,
                price: parseFloat(history.price || 0),
                stock: matchItem?.estimated_available_quantity || 0
              };
            });
    
            result.push(row);
          });
    
          this.chartData = result;
          this.updateEchart();
        },
        */


        // generate_data(days = 7, startDate = null, endDate = null, max_counts=false){
        //      let start, end;
        //   if (startDate && endDate) {
        //     start = new Date(startDate);
        //     end = new Date(endDate);
        //   } else {
        //     end = new Date();
        //     start = new Date();
        //     start.setDate(end.getDate() - (days - 1));
        //   }

        //   const allDates = [];
        //   const current = new Date(start);
        //   while (current <= end) {
        //     allDates.push(new Date(current));
        //     current.setDate(current.getDate() + 1);
        //   }

        //   let displayDates = allDates;

        //   if (max_counts){
        //     if (allDates.length > max_counts) {
        //     const step = Math.floor((allDates.length - 1) / max_counts -1);
        //     const selected = [];
        //     for (let i = 0; i < max_counts -1; i++) {
        //       selected.push(allDates[i * step]);
        //     }
        //     selected.push(allDates[allDates.length - 1]);
        //     displayDates = selected;
        //   }
        //   }
        //   return displayDates
        // },

        // generateMockData(days = 7, startDate = null, endDate = null) {
        // //   const res = this.all_data || {};
        // //   const allItems = [...(res.our_listing || []), ...(res.compete_listing || [])];
        // //   const allProductNames = [...this.ourProductList, ...this.competeProductList].map(p => p.label);

        //   const result = [];
        //   const displayDates = this.generate_data(days, startDate, endDate, 30)

        //   displayDates.forEach(date => {
        //     const month = (date.getMonth() + 1).toString().padStart(2, '0');
        //     const day = date.getDate().toString().padStart(2, '0');
        //     const shortDate = `${month}-${day}`;
        //     const year = date.getFullYear();
        //     const fullDate = `${year}-${month}-${day}`;
        //     const row = { date: shortDate };

        //     let tableCell = {}
        //     tableCell.date = fullDate

        //     [this.competeProductList, this.ourProductList].forEach(product => {
        //         const history = product?.history_json?.[fullDate] || { sales: 0, aver_price: 0, weighted_avg_price: 0, gmv:0, counts_percent: 0 };
        //         row[product.label] = {
        //             sales: history.sales || 0,
        //             aver_price: history.aver_price || 0,
        //             weighted_avg_price: parseFloat(history.weighted_avg_price || 0),
        //             gmv: history.gmv || 0,
        //             counts_percent: parseFloat(history.counts_percent || 0),
        //       }; 
        //     })

        //     Object.keys(row).forEach(key => {
        //     if (key !== 'date') {
        //         tableCell[key] = {};
        //         [this.competeProductList, this.ourProductList].forEach(product => {
        //         tableCell[key][product.label] = row[product.label][key];
        //         });
        //     }
        //     });

        //     result.push(row);
        //   });

        //   this.chartData = result;

        //   console.log("this.chartData==>", this.chartData)
        //   this.updateEchart();
        // },

        /**
         * 生成 days 天数内的所有日期
         * @param {number} [days=7] 生成数据的天数
         * @param {Date} [startDate=null] 生成数据的开始日期
         * @param {Date} [endDate=null] 生成数据的结束日期
         * @param {boolean | number} [max_counts=false] 生成数据的最大个数，如果为false，表示不限制
         * @returns {{ allDates: Date[], displayDates: Date[] }}  allDates 表示所有日期，displayDates 表示需要显示的日期
         */
        generate_data(days = 7, startDate = null, endDate = null, max_counts = false) {
            let start, end;
            if (startDate && endDate) {
                start = new Date(startDate);
                end = new Date(endDate);
            } else {
                end = new Date();
                start = new Date();
                start.setDate(end.getDate() - (days - 1));
            }

            const allDates = [];
            const current = new Date(start);
            while (current <= end) {
                allDates.push(new Date(current));
                current.setDate(current.getDate() + 1);
            }

            let displayDates = allDates;

            if (max_counts && allDates.length > max_counts) {
                const step = Math.floor((allDates.length - 1) / (max_counts - 1));
                const selected = [];
                for (let i = 0; i < max_counts - 1; i++) {
                    selected.push(allDates[i * step]);
                }
                selected.push(allDates[allDates.length - 1]);
                displayDates = selected;
            }

            return { allDates, displayDates };
        },


        /**
         * 生成Mock数据
         * @param {number} [days=7] 生成数据的天数
         * @param {Date} [startDate=null] 生成数据的开始日期
         * @param {Date} [endDate=null] 生成数据的结束日期
         * @returns {void}
         */
        generateMockData(days = 7, startDate = null, endDate = null) {
            const { allDates, displayDates } = this.generate_data(days, startDate, endDate, 30);

            const tableData = [];
            const chartData = [];

            allDates.forEach(date => {
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const shortDate = `${month}-${day}`;
                const year = date.getFullYear();
                const fullDate = `${year}-${month}-${day}`;

                const row = { date: shortDate };
                const tableRow = { date: fullDate };

                [this.competeProductList, this.ourProductList].forEach(product => {
                        const history = product?.history_json?.[fullDate] || {
                         listing_count: 0,   sales: 0, aver_price: 0, weighted_avg_price: 0, gmv: 0, counts_percent: 0
                        };
                        const item = {
                            listing_count: history.listing_count || 0,
                            sales: history.sales || 0,
                            aver_price: history.aver_price || 0,
                            weighted_avg_price: parseFloat(history.weighted_avg_price || 0),
                            gmv: history.gmv || 0,
                            counts_percent: parseFloat(history.counts_percent || 0),
                        };

                        row[product.label] = item;

                        Object.entries(item).forEach(([key, value]) => {
                            if (key !== 'date' && history.aver_price > 0) {
                                tableRow[key] = tableRow[key] ?? {};
                                tableRow[key][product.type] = value;
                                if(key == 'counts_percent'){
                                    tableRow[key][product.type] = `${(tableRow[key][product.type] * 100).toFixed(2)} %`
                                }
                            }
                        })
                });

                if (tableRow.aver_price){
                    tableData.push(tableRow);
                }
                if (displayDates.find(d => d.toDateString() === date.toDateString())) {
                    chartData.push(row);
                }
            });

            this.tableData = []

            this.tableData = tableData.reverse();
            this.chartData = chartData;
            this.updateEchart();
        },



        updateEchart() {
            const dates = this.chartData.map(i => i.date);
            this.dateRangeTip = dates.length > 0 ? `${dates[0]} 至 ${dates[dates.length - 1]}` : '';

            const series = this.selectedProducts.map((productName, index) => {
                const data = this.chartData.map(day => day[productName]?.[this.currentField] || 0);

                console.log("productName==>", productName)
                const colors = ['#5470C6', '#91CC75', '#FAC858', '#73C0DE', '#3BA272'];
                return {
                    name: productName,
                    type: this.chartType,
                    data,
                    smooth: this.chartType === 'line',
                    itemStyle: { color: productName.includes('竞品') ? '#EE6666' : colors[index % colors.length] }
                };
            });

            this.chartOptions = {
                tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
                legend: {
                    data: this.selectedProducts,
                    top: 25,
                    left: 'center',
                    textStyle: { fontSize: 14 }
                },
                grid: { top: '60px', left: '60px', right: '60px', bottom: '50px' },
                xAxis: {
                    type: 'category',
                    data: dates,
                    axisLabel: { rotate: 45, interval: 0 }
                },
                yAxis: {
                    type: 'value',
                    name: this.dataFields[this.currentField],
                    axisLine: { lineStyle: { color: '#5470C6' } }
                },
                series
            };
        }
    }
};
</script>

<style scoped>
.details-items {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: space-between;
    
}
.compete {
    color:#E6A23C 
}
.our {
    color: #409EFF
}
</style>

<style>
.aver_analyze_detail_dialog .el-dialog__body {
    padding-top: 10px !important;
}
</style>